package cn.fanqinghong.basic.service.impl;


import cn.fanqinghong.basic.constants.BaseConstants;
import cn.fanqinghong.basic.dto.LoginDto;
import cn.fanqinghong.basic.dto.WeChatDto;
import cn.fanqinghong.basic.exception.BusinessException;
import cn.fanqinghong.basic.jwt.JwtUtils;
import cn.fanqinghong.basic.jwt.LoginResult;
import cn.fanqinghong.basic.jwt.RsaUtils;
import cn.fanqinghong.basic.service.ILoginService;
import cn.fanqinghong.basic.util.AjaxResult;
import cn.fanqinghong.basic.util.HttpClientUtils;
import cn.fanqinghong.basic.util.MD5Utils;
import cn.fanqinghong.basic.util.StrUtils;
import cn.fanqinghong.system.domain.Menu;
import cn.fanqinghong.system.mapper.MenuMapper;
import cn.fanqinghong.system.mapper.PermissionMapper;
import cn.fanqinghong.user.domain.Logininfo;
import cn.fanqinghong.user.domain.User;
import cn.fanqinghong.user.domain.Wxuser;
import cn.fanqinghong.user.mapper.LogininfoMapper;
import cn.fanqinghong.user.mapper.UserMapper;
import cn.fanqinghong.user.mapper.WxuserMapper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * FAN
 * 2022/6/18  12:26
 */
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 账号密码登录
     * @param dto
     * @return
     */
    @Override
    public Map<String, Object> account(LoginDto dto) {
        //1.数据空校验
        String password = dto.getPassword();
        String username = dto.getUsername();
        Integer type = dto.getType();
        if (StringUtils.isEmpty(password) || StringUtils.isEmpty(username) || StringUtils.isEmpty(type)){
            throw new BusinessException("参数不能为空");
        }
        //2.更具传入的username 和type 查询数据，并且username代表的数据库字段有三个 username phone email
        Logininfo logininfo = logininfoMapper.loadByUsernameAndType(username,type);
            //2.1 如果查询不到报错（用户不正确)
        if (logininfo == null){
            throw new BusinessException("用户不正确");
        }
            //2.2 查询到了数据，继续执行代码，校验密码是否一致
        String salt = logininfo.getSalt();
        //对密码进行加密
        String md5Pwd = MD5Utils.encrypByMd5(password + salt);
        //3.校验密码是否正确
        if (!md5Pwd.equals(logininfo.getPassword())){
            throw new BusinessException("用户名或者密码不正确");
        }
        //4.登录成功
        return logininfoSuccessHandler(logininfo);

        //4.登录成功
        //4.1 存储redis
       /* String token = UUID.randomUUID().toString();//获取本项目唯一的不重复的uuid作为key
        System.out.println(token);
        System.out.println(logininfo);
        redisTemplate.opsForValue().set(
                token,
                logininfo,//对象要序列化
                30,
                TimeUnit.MINUTES
        );
        //4.2 返回token + logininfo
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        //设置盐值为null
        logininfo.setSalt(null);
        //设置密码为null
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        return map;*/
    }

    /**
     * 处理登录成功之后的逻辑，给登陆人赋予权限
     * @param logininfo
     * @return
     */
    private Map<String,Object> logininfoSuccessHandler(Logininfo logininfo) {
        LoginResult loginResult = new LoginResult();
        loginResult.setLogininfo(logininfo);
        //如果登陆人是员工
        if(logininfo.getType() == 0){
            //获取到登陆人的菜单权限
            List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
            //获取到登陆人的按钮权限
            List<String> permissions = permissionMapper.loadPermissionByLogininfoId(logininfo.getId());
            //使用一个loginResult的对象来封装数据
            loginResult.setMenus(menus);
            loginResult.setPermissions(permissions);
        }

        //把登录人信息 + 权限 加密封装成JWT串，返回给前端
        //获取私钥
        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa").getFile());
//        PrivateKey privateKey = RsaUtils.getPrivateKey(JwtRasHolder.INSTANCE.getJwtRsaPrivateData());
        String jwtStr = JwtUtils.generateTokenExpireInMinutes(loginResult, privateKey, 24*60*60);
        Map<String, Object> map = new HashMap<>();
        map.put("token",jwtStr);
        //设置盐值为null
        logininfo.setSalt(null);
        //设置密码为null
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);
        map.put("menus",loginResult.getMenus());
        map.put("permissions",loginResult.getPermissions());
        return map;

    }

    /**
     * 微信扫码登录
     * @param dto
     * @return
     */
    @Override
    public AjaxResult wechat(WeChatDto dto) {
        //1.空验证
        String code = dto.getCode();
        if (code == null){
            throw new BusinessException("code不为空!!");
        }
        //2.通过code从微信获取token+openid
        String tokenUrl = BaseConstants.WechatConstants.TOKEN_URL
                .replace("APPID", BaseConstants.WechatConstants.APPID)
                .replace("SECRET", BaseConstants.WechatConstants.SECRET)
                .replace("CODE", code);
        String tokenStr = HttpClientUtils.httpGet(tokenUrl);
        //2.1 把请求得到的数据转换为JSON对象
        JSONObject tokenObj = JSON.parseObject(tokenStr);
        //2.2 获取到JSON对象中的access_token和openid数据
        String accessToken = tokenObj.getString("access_token");
        String openId = tokenObj.getString("openid");
        //3.通过openId查询t_wxuser的数据
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        //3.1 有，且userId存在，直接免密登录===第二次之后的扫码登录
        if (wxuser != null && wxuser.getUserId() != null){
            //wxuser.getUserId()获取到的是userId
            Logininfo logininfo = logininfoMapper.loadByUserId(wxuser.getUserId());
            //4.1 存储redis
            /*String token = UUID.randomUUID().toString();//获取本项目唯一的不重复的uuid作为key
            System.out.println(token);
            System.out.println(logininfo);
            redisTemplate.opsForValue().set(
                    token,
                    logininfo,//对象要序列化
                    30,
                    TimeUnit.MINUTES
            );
            //4.2 返回token + logininfo
            Map<String, Object> map = new HashMap<>();
            map.put("token",token);
            //设置盐值为null
            logininfo.setSalt(null);
            //设置密码为null
            logininfo.setPassword(null);
            map.put("logininfo",logininfo);*/
            return AjaxResult.me().setResultObj(logininfoSuccessHandler(logininfo));
        }
        //3.2 没有，这里应该让浏览器跳转到绑定页面，让它自己输入账号和密码来完成绑定
        //返回token+openid
        String binderParams = "?accessToken=" + accessToken +"&openId=" + openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderParams);
    }

    /**
     * 账号绑定
     * @param dto
     * @return
     */
    @Override
    public Map<String,Object> binder(WeChatDto dto) {
        String phone = dto.getPhone();
        String accessToken = dto.getAccessToken();
        String openId = dto.getOpenId();
        String verifyCode = dto.getVerifyCode();
        if (StringUtils.isEmpty(phone)){
            throw new BusinessException("参数不能为空!!!");
        }
        //获取到储存的电话的key
        String phoneBinder = BaseConstants.WechatConstants.BINDER_SMS_PREFIX + phone;
        //查询redis、中存储的值
        Object phoneTme = redisTemplate.opsForValue().get(phoneBinder);
        //字符串化得到的对象
        String phoneStr = phoneTme.toString();
        //分割得到验证码
        String phoneCode = phoneStr.split(":")[0];
        if (!verifyCode.equalsIgnoreCase(phoneCode)){
            throw new BusinessException("验证码不正确");
        }
//        1.根据username 查询t_user是否曾今已经存在

        User user = userMapper.loadByPhone(dto.getPhone());
        Logininfo logininfo = null;
//        1.1 存在 查询出来，等着绑定
        if (user != null){
            //1.1.1 通过user中的loininfoId查询到logininfo的数据
            logininfo = logininfoMapper.loadById(user.getLogininfoId());
        }else{
            //不存在
//            1.2 不存在 生成新的t_user + t_logininfo
            user = dto2User(dto);
            logininfo = user2Logininfo(user);
            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
//        2.根据token + openid 去微信查询微信的用户基本信息   ③
        //2.1 获取到发送请求的路径
        String wxuserUrl = BaseConstants.WechatConstants.WXUSER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
//        3.根据微信的用户基本信息生成t_wxuser
        //3.1发送请求，获取微信账号信息
        String wxuserStr = HttpClientUtils.httpGet(wxuserUrl);
        Wxuser wxuser = JSON.parseObject(wxuserStr, Wxuser.class);
//        4.t_wxuser绑定t_user
        wxuser.setUserId(user.getId());
//        5.保存t_wxuser（完成了整个绑定流程）
        wxuserMapper.save(wxuser);
//        6.直接免密登录
        /*//声明一个uuid
        String token = UUID.randomUUID().toString();
        //存储redis
        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
        );
        //创建一个map
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("logininfo",logininfo);
        //设置盐值和密码为null
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        return map;*/
        return logininfoSuccessHandler(logininfo);
    }

    /**
     * 设置Logininfo中的数据
     * @param user
     * @return
     */
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);//这里设置的是用户 1
        return logininfo;
    }

    /**
     * 设置User中的数据
     * @param dto
     * @return
     */
    private User dto2User(WeChatDto dto) {
        User user = new User();
        //设置手机号
        user.setPhone(dto.getPhone());
        //设置username
        user.setUsername(dto.getPhone());
        //设置盐值
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        //设置加密密码
        user.setPassword(dto.getPassword() + salt);
        return user;
    }

}
